package com.yiboshi.rehrs.util.js;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import javax.crypto.Cipher;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class CipherPool {


    private static final Map<String,GenericObjectPool<Cipher>> poolMap = new ConcurrentHashMap<>();


    /*static {
        CipherPool.initialize(); // 必须提前初始化
    }*/


    public static Cipher borrowCipher(String transformation) throws Exception {
        if (poolMap.containsKey(transformation)) {
            return poolMap.get(transformation).borrowObject();
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(16); // 最大连接数
        config.setMinIdle(8);   // 最小空闲数
        config.setMaxIdle(8);  // 最大空闲数
        config.setMaxWaitMillis(1000); // 获取对象最大等待时间
        GenericObjectPool<Cipher> pool
                = new GenericObjectPool<>(new CipherFactory(transformation), config);
        poolMap.put(transformation, pool);
        return pool.borrowObject();
    }

    public static void returnCipher(Cipher cipher, String transformation) {
        if(cipher==null){
            return ;
        }
        try{
            poolMap.get(transformation).returnObject(cipher);
        }catch (Exception e){
            log.error("returnCipher error,{}",e.getMessage());
            cipher = null;
            //cipher.dispose();
        }

    }



}
